from time import sleep

import win32clipboard
import win32com.client
import win32con
from win32com.client.dynamic import CDispatch

import MYSQLUtils
import VAR

# 组件字段字典 在idea无法检索到的情况下回匹配以下字典
componentDict: dict = {
    "lot": "批次号",
    "receivedDate": "收货日期",
    "qcDate": "质检日期",
    "productDate": "生产日期",
    "nearDate": "近效日期",
    "expireDate": "过期日期",
    "asnCustomerBill": "ASN客户单号",
    "soiCode": "指定销售单",
    "supplierId": "供应商",
    "erpId": "ERP逻辑子库",
    "fifoBatch": "先进先出序号",
    "qeLevel": "货品等级",

    "itemId": "货品序号",
    "itemKeyId": "批次属性ID",
    "inventoryStatus": "库存状态",

    "baseQty": "记账单位数量",
    "packQty": "包装数量",
    "packageUnitId": "包装",
    "packageName": "包装名称",
    "convertFigure": "件装量",
    "buPrecision": "记账单位精度",

    "version": "版本号",
    "updateTime": "更新时间",
    "createdTime": "创建时间",
    "creator": "创建人",
    "creatorUnikey": "创建人外键",
    "lastOperator": "最后操作人",
    "lastOperatorUnikey": "最后操作人外键",
    "beDelete": "是否被删除",
    "beCancel": "是否取消",

    "contactName": "联系人",
    "telephone": "联系电话",
    "mobile": "手机号",
    "fax": "传真",
    "email": "邮箱",
    "postCode": "邮编",
    "country": "国家",
    "province": "省份",
    "city": "城市",
    "district": "区",
    "address": "地址",

    "palletNo": "托盘号",
    "boxNo": "周转箱号",
    "innerBoxNo": "内周转箱",
    "palletSeq": "托盘顺序",
    "boxSeq": "周转箱顺序",

    "id": "序号",


}


def bindIdea(dm: CDispatch):
    """
    绑定IDEA
    :return:
    """
    VAR.ideaHandle = dm.FindWindow("", "wms6-archetype")
    print("idea句柄:" + str(VAR.ideaHandle))
    isHandle: int = dm.BindWindow(VAR.ideaHandle, "normal", "normal", "normal", 0)
    if isHandle == 1:
        print("绑定成功")


def findPicAndMove(picPath: str, dm: CDispatch, handle: int, xAdd=0, yAdd=0):
    """
    查询到图像,并且鼠标移动至此处
    :return:
    """
    x1 = 0
    y1 = 0
    x2 = 0
    y2 = 0
    result: tuple = dm.GetWindowRect(handle, x1, y1, x2, y2)
    x1 = result[1]
    y1 = result[2]
    x2 = result[3]
    y2 = result[4]
    rx = 0
    ry = 0
    result: tuple = dm.FindPic(x1, y1, x2, y2, picPath, "000000", 1, 0, rx, ry)
    rx = result[1]
    ry = result[2]
    sleep(VAR.moveSleep)
    dm.MoveTo(rx + xAdd, ry + yAdd)
    sleep(VAR.moveSleep)
    print(result)
    return result[0]


def findClassCommentsByTableName(tableName: str, dm: CDispatch, handle: int):
    """
    按照表名从idea中获取类注释.
    :return:
    """
    print(tableName)


def waitPicRefresh(picPath: str, dm: CDispatch, handle: int):
    flag = -1
    count = 0
    """
    等待需要的图片出来
    :return:
    """
    while flag == -1:
        sleep(0.01)
        count = count + 1
        x1 = 0
        y1 = 0
        x2 = 0
        y2 = 0
        result: tuple = dm.GetWindowRect(handle, x1, y1, x2, y2)
        x1 = result[1]
        y1 = result[2]
        x2 = result[3]
        y2 = result[4]
        rx = 0
        ry = 0
        result: tuple = dm.FindPic(x1, y1, x2, y2, picPath, "000000", 1, 0, rx, ry)
        flag = result[0]
        print(result)
        if count > 10:
            raise BaseException("当前字段没有注释或者是组件")


def findAttrCommentsByTableNameAndAttrName(tableName: str, attrName: str, dm: CDispatch, handle: int):
    """
    按照表名和字段命从idea中获取字段注释.
    :return:
    """
    # 把表名转换成驼峰 首字母大写
    strlist = tableName.split("_")
    Strlist = [s.capitalize() for s in strlist]
    tableName = "".join(Strlist)
    # 把字段名改为驼峰 首字母小写
    strlist = attrName.split("_")
    Strlist = [s.capitalize() for s in strlist]
    attrName = "".join(Strlist)
    attrName = attrName[0].lower() + attrName[1:]
    # 校验当前字段是否为组件
    # 流程
    dm.SetWindowState(handle, 1)
    waitPicRefresh("D:\\code\\pythonProject\\DataMD\\idea_focus_index.bmp", dm, handle)
    findPicAndMove("D:\\code\\pythonProject\\DataMD\\idea_focus_index.bmp", dm, handle)
    dm.LeftClick()
    sleep(0.1)
    dm.KeyPress(16)
    sleep(0.1)
    dm.KeyPress(16)
    sleep(0.5)
    dm.KeyPress(16)
    sleep(0.1)
    dm.KeyPress(16)
    waitPicRefresh("D:\\code\\pythonProject\\DataMD\\idea_noproject_index.bmp", dm, handle)
    sleep(0.1)
    dm.SendString(handle, tableName + "." + attrName)
    sleep(1)
    try:
        waitPicRefresh("D:\\code\\pythonProject\\DataMD\\idea_attr_index.bmp", dm, handle)
    except BaseException:
        return getCommentFromComponentDictByAttrName(attrName)
    dm.KeyPressChar("enter")
    waitPicRefresh("D:\\code\\pythonProject\\DataMD\\idea_editfocus_index.bmp", dm, handle)
    sleep(0.1)
    dm.KeyDownChar("ctrl")
    dm.KeyPressChar("q")
    dm.KeyUpChar("ctrl")
    try:
        waitPicRefresh(
            "D:\\code\\pythonProject\\DataMD\idea_private_index.bmp|D:\\code\\pythonProject\\DataMD\\idea_private2_index.bmp",
            dm, handle)
    except BaseException:
        return "TODO:待手工校验"
    waitPicRefresh(
        "D:\\code\\pythonProject\\DataMD\idea_private_index.bmp|D:\\code\\pythonProject\\DataMD\\idea_private2_index.bmp",
        dm, handle)
    findPicAndMove(
        "D:\\code\\pythonProject\\DataMD\idea_private_index.bmp|D:\\code\\pythonProject\\DataMD\\idea_private2_index.bmp",
        dm, handle, xAdd=10, yAdd=30)
    sleep(0.1)
    dm.LeftDoubleClick()
    dm.LeftClick()
    sleep(0.1)
    dm.KeyDownChar("ctrl")
    dm.KeyPressChar("c")
    dm.KeyUpChar("ctrl")
    win32clipboard.OpenClipboard()
    text = win32clipboard.GetClipboardData(win32con.CF_UNICODETEXT)
    win32clipboard.CloseClipboard()
    dm.KeyPressChar("esc")
    dm.KeyDownChar("ctrl")
    dm.KeyPressChar("f4")
    dm.KeyUpChar("ctrl")
    return text


def getCommentFromComponentDictByAttrName(attrName: str) -> str:
    """
    使用属性名从组件字典中获取字段注释
    :return: 组件
    """
    for k, v in componentDict.items():
        # 如果一比一相同直接返回对应注释
        if k == attrName:
            return v
        # 字典首字母大写
        k: str = k[0].upper() + k[1:]
        if attrName.find(k) != -1 and (attrName[len(attrName) - len(k):] == k):
            return v
    return 'TODO:待手工校验'


if __name__ == '__main__':
    # 输出文档目录
    mdFileStr: str = 'D:/code/笔记/唯智/项目/bmwms/输出文档/八马数据字典.md'
    dm: CDispatch = win32com.client.Dispatch('dm.dmsoft')
    print("加载dm插件,版本号:" + str(dm.ver()))
    bindIdea(dm)
    # 先加载md文件
    mdFile = open(mdFileStr, encoding="utf-8", mode="r")
    # 读取到的内容
    markdown: str = mdFile.read()
    mdFile.close()

    # 读取最后一个表名
    strtemp: str = markdown[markdown.rindex("## "):]
    strtemp = strtemp[strtemp.index(":"):]
    lastTableName = strtemp[strtemp.index(":") + 1:strtemp.index("\n")]

    # 先获取到所有的表
    tables: tuple = MYSQLUtils.getAllTableName()
    for table in tables:
        # 匹配到当前表
        if lastTableName == table[0]:
            # 获取md中最后一张表的字符串
            lastTableAttName = markdown[markdown.rindex("|----|----|"):]
            # 获取字段并且匹配
            attrDatas = MYSQLUtils.getAllAttrByTableName(lastTableName)
            for attr in attrDatas:
                # 如果md表中没有这个字段才添加
                if lastTableAttName.find(attr[0]) == -1:
                    # 字段类型长度
                    attrType = MYSQLUtils.getAllAttrTypeAndSizeByTableNameAndAttrName(lastTableName, attr[0])[0][0]
                    # 注释
                    comment = findAttrCommentsByTableNameAndAttrName(lastTableName, attr[0], dm, VAR.ideaHandle)
                    markdown += "\n|" + attr[0] + "|" + comment + "|" + attrType + "|"
                    mdFile = open(mdFileStr, encoding="utf-8", mode="w")
                    mdFile.write(markdown)
                    mdFile.close()
            # 字段赋值完了以后,如果当前不是最后一张表
            if (tables.index(table) + 1) != tables.__sizeof__():
                # 开始绘制新表
                lastTableName = tables[tables.index(table) + 1][0]
                strlist = lastTableName.split("_")
                Strlist = [s.capitalize() for s in strlist]
                className = "".join(Strlist)
                markdown += "\n## TODO:" + lastTableName
                markdown += "\n|字段名|描述|类型|"
                markdown += "\n|----|----|----|"
                mdFile = open(mdFileStr, encoding="utf-8", mode="w")
                mdFile.write(markdown)
                mdFile.close()
